package com.tensquare.web.filter;

import cn.hutool.core.util.StrUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/7/30 15:23
 * 网关过滤器
 */
@Component
public class WebFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }
    //2.执行过滤器的逻辑
    @Override
    public Object run() throws ZuulException {
        //2.1)得到当前请求的上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.2)得到请求对象
        HttpServletRequest request = currentContext.getRequest();
        //2.3)得到请求头对象
        String header = request.getHeader("Authorization");
        //2.4)判断是否有数据
        if(StrUtil.isNotEmpty(header)){
            //2.4.1)如果有数据就添加到zull的网关的请求头上
            currentContext.addZuulRequestHeader("Authorization",header);
        }
        return null;
    }
}
